﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Vega.USiteBuilder;
using SPCFMedicineInformer.Members;
using umbraco.cms.businesslogic.member;

using System.Text;
using System.Data;
using SPCFMedicineInformer.Helpers;
using SPCFMedicineInformer;
using System.Web.Security;
using umbraco.cms.businesslogic.web;
using umbraco;

namespace SPCFMedicineInformer.Masterpages
{
    public partial class Admin_UserDetails : System.Web.UI.MasterPage
    {
        int id = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            int tempInt;
            id = Request.QueryString["id"] != null ? int.TryParse(Request.QueryString["id"].ToString(), out tempInt) ? tempInt : 1 : 0;
            bool isNewUser = Request.QueryString["n"] != null ? Request.QueryString["n"].ToString() == "1" ? true : false : false;
            btnDelete.Visible = id > 0 ? true : false;

            if (!IsPostBack)
            {
                LoadDates();
                if (id > 0)
                {
                    var m = MemberHelper.GetMemberById(id) as WebUser;
                    if (m != null)
                    {
                        txtEmail.Text = m.Email;
                        txtFirstname.Text = m.Fistname;
                        txtLastname.Text = m.Lastname;
                        rdoGender.Text = m.Gender;
                        txtAddress.Text = m.Address;


                        DateTime bDate;
                        if (DateTime.TryParse(m.Birthdate, out bDate))
                        {
                            ddlMonth.SelectedValue = bDate.Month.ToString();
                            ddlDay.SelectedValue = bDate.Day.ToString();
                            ddlYear.SelectedValue = bDate.Year.ToString();
                        }
                        if (isNewUser)
                            ShowSaveMessage();
                        ShowContent(true);
                    }
                    else
                    {
                        ShowContent(false);
                    }
                }
                else
                {
                    ShowNewPassword(true);
                }
            }
        }
        void ShowContent(bool b)
        {
            plcContent.Visible = b;
            plcError.Visible = !b;
        }
        void ShowNewPassword(bool b)
        {
            plcChangePassword.Visible = b;
            lbChangePassword.Visible = !b;
        }
        void Update()
        {
            if (id > 0)
            {
                var m = new Member(id);
                if (m != null)
                {
                    TransferDetailsToUmbraco(m);
                }

            }
        }
        int AddNewUser()
        {
            string birthdate = string.Concat(ddlMonth.Items[ddlMonth.SelectedIndex].Text, " ", ddlDay.Items[ddlDay.SelectedIndex].Text, " ,", ddlYear.Items[ddlYear.SelectedIndex].Text);
            var newMember = new WebUser(txtEmail.Text, txtEmail.Text, txtNewPassword.Text)
            {
                Fistname = txtFirstname.Text,
                Lastname = txtLastname.Text,
                Gender = rdoGender.Text,
                Address = txtAddress.Text,
                Birthdate = birthdate
            };
            newMember.Save();
            if (!Roles.RoleExists(Constants.Roles.ADMINISTRATOR))
                Roles.CreateRole(Constants.Roles.ADMINISTRATOR);

            Roles.AddUserToRole(newMember.LoginName, Constants.Roles.ADMINISTRATOR);
            return newMember.Id;
        }
        void TransferDetailsToUmbraco(Member m)
        {
            string birthdate = string.Concat(ddlMonth.Items[ddlMonth.SelectedIndex].Text, " ", ddlDay.Items[ddlDay.SelectedIndex].Text, " ,", ddlYear.Items[ddlYear.SelectedIndex].Text);
            m.Email = txtEmail.Text;
            m.LoginName = txtEmail.Text;
            if (plcChangePassword.Visible)
                m.Password = txtNewPassword.Text;
            m.getProperty(Constants.UmbracoPropertyName.MEMBER_FIRSTNAME).Value = txtFirstname.Text;
            m.getProperty(Constants.UmbracoPropertyName.MEMBER_LASTNAME).Value = txtLastname.Text;
            m.getProperty(Constants.UmbracoPropertyName.MEMBER_GENDER).Value = rdoGender.Text;
            m.getProperty(Constants.UmbracoPropertyName.MEMBER_ADDRESS).Value = txtAddress.Text;
            m.getProperty(Constants.UmbracoPropertyName.MEMBER_BIRTHDATE).Value = birthdate;
            m.Save();
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Helpers.FormValidation.ValidateRegistration(MsgLiteral,txtFirstname.Text,
                txtLastname.Text,txtNewPassword.Text,txtConfirmPassword.Text,txtEmail.Text,id,plcChangePassword.Visible,rdoGender.Text,ddlMonth,ddlDay,ddlYear))
            {
                if (id > 0)
                {
                    Update();
                    ShowSaveMessage();
                }    
                else
                {
                    id = AddNewUser();
                    Response.Redirect("/admin/users/admin-users/admin-user-details?id=" + id + "&n=1");
                }
            }
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/users/admin-users/");
        }
        protected void lbChangePassword_Click(object sender, EventArgs e)
        {
            ShowNewPassword(true);
        }
        void ShowSaveMessage()
        {
            var sb = new StringBuilder();
            var msgFormat = "<p class=\"{0}\">{1}</p>";
            sb.AppendLine(string.Format(msgFormat, "msg done", "User Successfully Saved!"));
            MsgLiteral.Visible = true;
            MsgLiteral.Text = sb.ToString();
            ShowNewPassword(false);
        }
        void Delete(int id)
        {
            if (id > 0)
            {
                Member m = new Member(id);
                if (m != null)
                {
                    m.delete();
                }
                Response.Redirect("/admin/users/admin-users/");
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Delete(id);
        }
        void LoadDates()
        {
            DateTime dteDefault = DateTime.Parse("1/1/2012");
            DataTable dtMonth = new DataTable();
            DataTable dtDay = new DataTable();
            DataTable dtYear = new DataTable();
            DataRow dr = null;

            dtMonth.Columns.Add(new DataColumn("TextField"));
            dtMonth.Columns.Add(new DataColumn("ValueField"));
            dtDay = dtMonth.Copy();
            dtYear = dtMonth.Copy();

            string textField = "TextField";
            string valueField = "ValueField";

            dr = dtMonth.NewRow();
            dr[textField] = "Month";
            dr[valueField] = "0";
            dtMonth.Rows.Add(dr);
            for (int mon = 1; mon <= 12; mon++)
            {
                dr = dtMonth.NewRow();
                dr[textField] = dteDefault.ToString("MMMM");
                dr[valueField] = mon;
                dtMonth.Rows.Add(dr);
                dteDefault = dteDefault.AddMonths(1);
            }


            dr = dtDay.NewRow();
            dr[textField] = "Day";
            dr[valueField] = "0";
            dtDay.Rows.Add(dr);
            for (int day = 1; day <= 31; day++)
            {
                dr = dtDay.NewRow();
                dr[textField] = day;
                dr[valueField] = day;
                dtDay.Rows.Add(dr);
            }

            dr = dtYear.NewRow();
            dr[textField] = "Year";
            dr[valueField] = "0";
            dtYear.Rows.Add(dr);
            for (int year = DateTime.Now.Year; year >= DateTime.Now.AddYears(-85).Year; year--)
            {
                dr = dtYear.NewRow();
                dr[textField] = year;
                dr[valueField] = year;
                dtYear.Rows.Add(dr);
            }

            FormHelper.BindDropDown(ddlDay, dtDay, textField, valueField);
            FormHelper.BindDropDown(ddlMonth, dtMonth, textField, valueField);
            FormHelper.BindDropDown(ddlYear, dtYear, textField, valueField);
        }
    }
}